import { createRouter, createWebHistory } from "vue-router";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/login",
      name: "login",
      component: () => import("../views/login.vue"),
    },
    {
      path: "/chat",
      name: "chat",
      component: () => import("../views/chat.vue"),
    },
    {
      path: "/chatroom",
      name: "chatroom",
      component: () => import("../views/chatRoom.vue"),
    },
    {
      path: "/:pathMatch(.*)*",
      redirect: "/login",
    },
  ],
});

router.beforeEach((to, from, next) => {
  const mode = sessionStorage.getItem("mode");

  if (mode === "chat" && to.name !== "chat") {
    next({ name: "chat" }); // 强制跳转到 /chat
  } else if (mode === "chatroom" && to.name !== "chatroom") {
    next({ name: "chatroom" }); // 强制跳转到 /chatroom
  } else if (!mode && to.name !== "login") {
    next({ name: "login" }); // 如果 mode 为空，强制跳转到 /login
  } else {
    next(); // 允许继续导航
  }
});

export default router;
